package com.fhc.view.text

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt

@Composable
fun <T> MovableTextBox(
    moveObject: T,
    boxName:String,
    txtColor:Color = Color.Black,
    bgColor:Color = Color.White,
    containerSize: IntSize,
    selfSize: DpSize,
    selfOffset: Offset,
    onDragMove: (T, Float, Float) -> Unit,
    onDragEnd: (T, Float, Float) -> Unit,
    onGloballyPositioned: (T, Offset) -> Unit,
    dataUpdated: Boolean = false,
    onClick: (T) -> Unit = {},
    unHighlight: Boolean = false,
) {
    var isHeatBeat by remember { mutableStateOf(dataUpdated) }
    var offset by remember { mutableStateOf(selfOffset) }
    LaunchedEffect(selfOffset) {
        offset = selfOffset
    }
    LaunchedEffect(dataUpdated) {
        isHeatBeat = dataUpdated
    }
    var isHighlight by remember { mutableStateOf(!unHighlight) }
    LaunchedEffect(unHighlight) {
        isHighlight = !unHighlight
    }
//    // 自定义Offset的Saver实现
//    val offsetSaver = run {
//        Saver<Offset, List<Float>>(
//            save = { listOf(it.x, it.y) },
//            restore = { Offset(it[0], it[1]) }
//        )
//    }

    // 使用带Saver的rememberSaveable
//    var offset by rememberSaveable(stateSaver = offsetSaver) {
//        mutableStateOf(selfOffset)
//    }
//    var offset by remember { mutableStateOf(selfOffset) }


    val context = LocalDensity.current
    // 性能优化：使用派生状态减少计算次数
    val maxOffset by remember(containerSize) {
        derivedStateOf {
            with(context) {
                Offset(
                    containerSize.width.toFloat() - selfSize.width.toPx(),
                    containerSize.height.toFloat() - selfSize.height.toPx()
                )
            }
        }
    }


    // 拖动逻辑优化：使用协程防抖
    val scope = rememberCoroutineScope()
    var lastDragJob by remember { mutableStateOf<Job?>(null) }

    // 心跳动画
    val heartbeatAnimation = remember { Animatable(1f) }
    LaunchedEffect(isHeatBeat) {
        if (isHeatBeat) {
            // 运行1.5秒的心跳动画 (3次跳动，每次500ms)
            repeat(3) {
                heartbeatAnimation.animateTo(
                    targetValue = 0.5f,
                    animationSpec = tween(250)
                )
                heartbeatAnimation.animateTo(
                    targetValue = 1f,
                    animationSpec = tween(250)
                )
            }
        }
    }
    // 记住交互源
    val interactionSource = remember { MutableInteractionSource() }

    Box(
        modifier = Modifier.offset { IntOffset(offset.x.roundToInt(), offset.y.roundToInt()) }

            .graphicsLayer {
                scaleX = if(isHeatBeat) heartbeatAnimation.value else 1f
                scaleY = if(isHeatBeat) heartbeatAnimation.value else 1f
                transformOrigin = TransformOrigin.Center
                clip = false
            }
            .size(selfSize.width, selfSize.height)
            .clip(RoundedCornerShape(6.dp))
            .background(bgColor.copy(alpha =(if(!isHighlight) 0.3f else 1f)))
            .clickable(
                interactionSource = interactionSource,
                indication = LocalIndication.current,
                onClick = {
                    onClick(moveObject)
                }
            )
            .pointerInput(moveObject) { // 添加device作为key，设备变化时重置手势
                detectDragGestures(
                    onDragStart = { /* 可添加拖动开始回调 */ },
                    onDrag = { _, dragAmount ->
                        offset = Offset(
                            x = (offset.x + dragAmount.x).coerceIn(0f, maxOffset.x),
                            y = (offset.y + dragAmount.y).coerceIn(0f, maxOffset.y)
                        )

                        // 防抖处理：取消前一个未完成的拖动事件
                        lastDragJob?.cancel()
                        lastDragJob = scope.launch {
                            delay(4) // 12约60FPS的间隔
                            onDragMove(moveObject, offset.x, offset.y)
                        }
                    },
                    onDragEnd = {
                        lastDragJob?.cancel() // 确保最终位置被提交
                        onDragEnd(moveObject, offset.x, offset.y)
                    }
                )
            }.onGloballyPositioned {
                onGloballyPositioned(moveObject, offset) // 使用当前offset而非device原始值
            }
    ) {
        Text(
            text = boxName,
            modifier = Modifier.fillMaxSize().wrapContentHeight(Alignment.CenterVertically), // 垂
            color = txtColor.copy(alpha =(if(!isHighlight) 0.3f else 1f)),
            fontSize = 16.sp,
            fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center,
            style = MaterialTheme.typography.titleLarge
        )
    }
}

